package dk.sdu.mmmi.opn.assignment3easy.server;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import dk.sdu.mmmi.opn.assignment3easy.acquaintance.ICatalogue;
import dk.sdu.mmmi.opn.assignment3easy.acquaintance.IEntry;
import dk.sdu.mmmi.opn.assignment3easy.acquaintance.Product;
import dk.sdu.mmmi.opn.rmi.observer.RemoteObservable;

/**
 * Implementation of a catalogue
 * (part of the model layer of the application)
 * @author ups
 */
public class CatalogueImpl extends RemoteObservable implements ICatalogue {

	/**
	 * Contents of the catalogue
	 */
	private Map<String,EntryImpl> stock = new HashMap<String,EntryImpl>();
	
	/**
	 * Create and initialize the stock
	 */
	public CatalogueImpl() throws RemoteException {
		initializeStock();
	}
	
	/**
	 * Lookup entry by name
	 */
	@Override
	public IEntry getEntry(String name) {
		Server.log(false, "CatalogueImpl::getEntry "+name);
		return stock.get(name);
	}

	/**
	 * Search catalogue and return all products that match the given prefix
	 */
	@Override
	public List<Product> search(String pattern) {
		Server.log(false, "CatalogueImpl::search "+pattern);
		ArrayList<Product> result = new ArrayList<Product>();
		for(Map.Entry<String, EntryImpl> entry: stock.entrySet())
			if(entry.getKey().startsWith(pattern)) result.add(entry.getValue().local_getProduct());
		return result;
	}

	/**
	 * Get all names of entries
	 */
	@Override
	public Set<String> getEntryNames() {
		Server.log(false, "CatalogueImpl::getEntryNames");
		return new HashSet<String>(stock.keySet());
	}

	/**
	 * Initialize stock with dummy products
	 */
	private void initializeStock() throws RemoteException {
		Random random = new Random();
		for(int i=0; i<PRODUCTNAMES.length; i++)
			stock.put(PRODUCTNAMES[i],new EntryImpl(this,new Product(PRODUCTNAMES[i],random.nextInt(1000)/100.0f),random.nextInt(10)));
	}
	
	private static final String[] PRODUCTNAMES = { 
		"cucumber", "carrot", "potato", "pear", "apple", "zucchini", "beet", "onion", "tomato", "orange", "banana", "grapes", "sweet potato",
		"garlic", "lemon", "lime", "cabbage", "corn"
	};

	private static final long serialVersionUID = -7039445168449205914L;
}
